/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-15 Time: 23:16
 *
 * 新建报修工单
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    TouchableOpacity,
    ScrollView, AsyncStorage, Modal, TextInput,
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from './ConsumablesScreen.Style';
import {getRecordSum} from './Actions'
import {FetchStatus} from "../../../../../../configuration/RequestConfiguration";
import LoadingView from "../../../../../../component/LoadingView/LoadingView";
import RepairWorkOrderChooseConsumablesScreen from "../../../RepairWorkOrderChooseConsumablesScreen/RepairWorkOrderChooseConsumablesScreen"
import {materialRecordOut,retrieveMaterialBySn} from "./Actions";
import {ReturnStatus} from "../../../../../../configuration/ReturnStatus";
import {doDisplaySuccessMessage, doDisplayWarnMessage} from "../../../../../../component/Message/Action";
import AntDesign from "react-native-vector-icons/AntDesign";
import {COLOR_GRAY_LINE, FONT_COLOR_SUB_TITLE} from "../../../../../../constant/PHColors";
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";

class ConsumablesScreen extends Component {

    static navigationOptions = ({navigation}) => ({
        title: '耗材记录',
    });

    //构造
    constructor(props) {
        super(props);
        this.state = {
            recordSum:[], //当前耗材记录
            newRecordSum:[], //修改后耗材记录
            recordVisiable:true, //当前耗材记录页面
            chooseConsumablesVisiable:false,//选择耗材
            recordClickModal:false, //列表点击事件
            selectState:"出仓",
            recordClickModalBalance:0, //列表点击库存
            recordClickModalQuantity:0, //列表点击已出仓数量
            recordClickModalSn:'', //列表点击Sn
            textInputNum:'0',
            textInputLeftBtnColor:COLOR_GRAY_LINE,
        }
    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;
        let _this = this;
        if (nextProps.onGetRecordSum !== this.props.onGetRecordSum && nextProps.onGetRecordSum.fetchStatus === FetchStatus.Success) {
            let recordSum = JSON.stringify(nextProps.onGetRecordSum.DATA);
            let recordSumJson = JSON.parse(recordSum);
            this.setState({
                recordSum:recordSumJson,
                newRecordSum:recordSumJson,
            })
        }

        if (nextProps.onMaterialRecordOut !== this.props.onMaterialRecordOut && nextProps.onMaterialRecordOut.fetchStatus === FetchStatus.Success) {
            if (nextProps.onMaterialRecordOut.RETURN === Number(ReturnStatus.Success)) {
                doDisplaySuccessMessage(nextProps.onMaterialRecordOut.MSG);
                this.props.navigation.navigate(this.props.navigation.getParam("beforePage"));
                this.props.navigation.state.params.goBack();
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onMaterialRecordOut.MSG))
            }
        }

        if (nextProps.onRetrieveMaterialBySn !== this.props.onRetrieveMaterialBySn && nextProps.onRetrieveMaterialBySn.fetchStatus === FetchStatus.Success) {
            if (Number(nextProps.onRetrieveMaterialBySn.RETURN) === Number(ReturnStatus.Success)) {
                AsyncStorage.getItem('chooseConsumables' ,function (error, result) {
                    if (error) {
                        alert('读取失败')
                    }else {
                        console.log(nextProps.onRetrieveMaterialBySn.DATA[0])

                        let newJSON = JSON.parse(result);
                        let selectState = '出仓';
                        let textInputLeftBtnColor = COLOR_GRAY_LINE;
                        let textInputRightBtnColor = FONT_COLOR_SUB_TITLE;
                        let textInputNum = '0';
                        if(newJSON[nextProps.onRetrieveMaterialBySn.DATA[0].sn]){
                            if(Number(newJSON[nextProps.onRetrieveMaterialBySn.DATA[0].sn]['quantity'])<0){
                                selectState='返仓';
                                textInputNum = Math.abs(Number(newJSON[nextProps.onRetrieveMaterialBySn.DATA[0].sn]['quantity'])).toString();
                                if(Math.abs(Number(newJSON[nextProps.onRetrieveMaterialBySn.DATA[0].sn]['quantity']))===1){
                                    if(nextProps.onRetrieveMaterialBySn.DATA[0].balance==='1'){
                                        textInputLeftBtnColor = COLOR_GRAY_LINE;
                                        textInputRightBtnColor = COLOR_GRAY_LINE;
                                    }else{
                                        textInputLeftBtnColor = COLOR_GRAY_LINE;
                                        textInputRightBtnColor = FONT_COLOR_SUB_TITLE;
                                    }
                                }else if(Math.abs(Number(newJSON[nextProps.onRetrieveMaterialBySn.DATA[0].sn]['quantity']))===nextProps.onRetrieveMaterialBySn.DATA[0].balance){
                                    textInputLeftBtnColor = FONT_COLOR_SUB_TITLE;
                                    textInputRightBtnColor = COLOR_GRAY_LINE;
                                }else{
                                    textInputLeftBtnColor = FONT_COLOR_SUB_TITLE;
                                    textInputRightBtnColor = FONT_COLOR_SUB_TITLE;
                                }
                            }else if(Number(newJSON[nextProps.onRetrieveMaterialBySn.DATA[0].sn]['quantity'])>0){
                                selectState='出仓';
                                textInputLeftBtnColor = FONT_COLOR_SUB_TITLE;
                                textInputRightBtnColor = FONT_COLOR_SUB_TITLE;
                                textInputNum = Math.abs(Number(newJSON[nextProps.onRetrieveMaterialBySn.DATA[0].sn]['quantity'])).toString();
                            }else if(Number(newJSON[nextProps.onRetrieveMaterialBySn.DATA[0].sn]['quantity'])===0){
                                selectState='出仓';
                                textInputLeftBtnColor = COLOR_GRAY_LINE;
                                textInputRightBtnColor = FONT_COLOR_SUB_TITLE;
                                textInputNum = '0';
                            }
                        }
                        _this.setState({
                            selectState:selectState,
                            textInputLeftBtnColor:textInputLeftBtnColor,
                            textInputRightBtnColor:textInputRightBtnColor,
                            textInputNum:textInputNum,
                            recordClickModalBalance:nextProps.onRetrieveMaterialBySn.DATA[0].balance,
                            recordClickModal:true,
                        })

                    }
                })

            } else {
                dispatch(doDisplayWarnMessage(nextProps.onRetrieveMaterialBySn.MSG))
            }
        }


    }

    componentWillMount() {//将要被挂载
        let value = '{}';
        AsyncStorage.setItem('chooseConsumables', value)
    };

    componentWillUnmount() {//销毁
        AsyncStorage.removeItem('chooseConsumables')
    };

    componentDidMount(): void {
        let {dispatch} = this.props;
        let str = {"arg":{"SQLfields":""},"where":{"record_sn":this.props.navigation.getParam("sn")}};
        dispatch(getRecordSum(JSON.stringify(str)))
    }

    render(){
        let _this = this;
        let {onGetRecordSum} = this.props;
        if (onGetRecordSum.fetchStatus !== FetchStatus.Success) {
            return <LoadingView/>
        }else{
            return (
                <SafeAreaView style={styles.body}>
                    {
                        this.state.recordVisiable && (
                            <View style={{flex:1,}}>
                                <ScrollView style={styles.bodyContainer}>
                                    {this.state.newRecordSum.length>0&&this.state.newRecordSum.map((value,index)=>{
                                        return this._renderRecord(value, index)
                                    })}
                                    {this.state.newRecordSum.length===0&&
                                    (
                                        <View style={styles.noRecord}>
                                            <Text style={styles.noRecordText}>
                                                选择耗材点击下方添加
                                            </Text>
                                        </View>
                                    )
                                    }
                                </ScrollView>
                                <View style={styles.bodyBottom}>
                                    <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                        // this.props.navigation.navigate('RepairWorkOrderChooseConsumablesScreen')
                                        this.setState({
                                            chooseConsumablesVisiable:true,
                                            recordVisiable:false,
                                        })
                                    }}>
                                        <View style={styles.bodyBottomLeft}>
                                            <Text style={styles.bodyBottomLeftText}>
                                                添加耗材
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                    <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                        this.finishAdd();
                                    }}>
                                        <View style={styles.bodyBottomRight}>
                                            <Text style={styles.bodyBottomRightText}>
                                                完成添加
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        )
                    }
                    {
                        this.state.chooseConsumablesVisiable &&  <RepairWorkOrderChooseConsumablesScreen
                            closeBack={()=>{
                                _this.showRecordVisiable()
                            }}
                            returnBack={(data)=>{
                                _this.showRecordVisiable();
                                _this.getNewRecordSum(data);
                            }}
                        />
                    }

                    {/*选择*/}
                    <Modal visible={this.state.recordClickModal} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()}>
                        <TouchableOpacity style={{flex: 1}} activeOpacity={1}  onPress={()=>{
                            this.onRequestClose();
                        }}>
                            <View style={styles.modalContainer}>
                                <View style={styles.modalBox} >
                                    <TouchableOpacity activeOpacity={1} onPress={()=>{
                                    }}>
                                        <View style={styles.modalTitle}>
                                            <Text style={styles.modalTitleTextNum}>
                                                出仓/返仓
                                            </Text>
                                        </View>
                                        <View style={styles.modalCenter}>
                                            <TouchableOpacity activeOpacity={1} onPress={()=>{
                                                this.setState({
                                                    selectState:"出仓",
                                                    textInputLeftBtnColor:COLOR_GRAY_LINE,
                                                    textInputRightBtnColor:FONT_COLOR_SUB_TITLE,
                                                    textInputNum:'0',
                                                })
                                            }}>
                                                <View style={{flexDirection:'row'}} >
                                                    <Text style={styles.modalCenterText}>
                                                        出仓（库存：{this.state.recordClickModalBalance}）
                                                    </Text>
                                                    {this._selectState("出仓")}
                                                </View>
                                            </TouchableOpacity>
                                            {
                                                this.state.selectState==="出仓" && (
                                                    <View style={{flexDirection:'row',marginTop: 10,marginBottom: 10}}>
                                                        <AntDesign name={'minuscircle'} onPress={()=>{
                                                            let num = Number(this.state.textInputNum)-1;
                                                            if(num>=0){
                                                                if(num===0){
                                                                    this.setState({textInputNum : num.toString(),textInputLeftBtnColor:COLOR_GRAY_LINE})
                                                                }else{
                                                                    this.setState({textInputNum : num.toString(),textInputLeftBtnColor:FONT_COLOR_SUB_TITLE})
                                                                }
                                                            }
                                                        }} size={25} style={{color: this.state.textInputLeftBtnColor}}/>
                                                        <TextInput style={styles.modalInput}
                                                                   keyboardType='numeric'
                                                                   textAlign='center'
                                                                   onChangeText={text => {
                                                                       if(Number(text)<0){
                                                                           text = '1'
                                                                       }
                                                                       this.setState({
                                                                           textInputNum : text,
                                                                       })
                                                                   }}
                                                                   defaultValue={this.state.textInputNum}
                                                        />
                                                        <AntDesign name={'pluscircle'} onPress={()=>{
                                                            let num = Number(this.state.textInputNum)+1;
                                                            this.setState({
                                                                textInputNum : num.toString(),
                                                                textInputLeftBtnColor:FONT_COLOR_SUB_TITLE,
                                                            })
                                                        }} size={25} style={{color: FONT_COLOR_SUB_TITLE}}/>
                                                    </View>
                                                )
                                            }
                                            <TouchableOpacity activeOpacity={1} onPress={()=>{
                                                this.setState({
                                                    selectState:"返仓",
                                                    textInputLeftBtnColor:FONT_COLOR_SUB_TITLE,
                                                    textInputRightBtnColor:COLOR_GRAY_LINE,
                                                    textInputNum:this.state.recordClickModalQuantity.toString(),
                                                })
                                            }}>
                                                <View style={{flexDirection:'row',marginTop:10}} >
                                                    <Text style={styles.modalCenterText}>
                                                        返仓（已出仓数量：{this.state.recordClickModalQuantity}）
                                                    </Text>
                                                    {this._selectState("返仓")}
                                                </View>
                                            </TouchableOpacity>
                                            {
                                                this.state.selectState==="返仓" && (
                                                    <View style={{flexDirection:'row',marginTop: 10,marginBottom: 10}}>
                                                        <AntDesign name={'minuscircle'} onPress={()=>{
                                                            let num = Number(this.state.textInputNum)-1;
                                                            if(num>0){
                                                                if(num===1){
                                                                    this.setState({textInputNum : num.toString(),textInputLeftBtnColor:COLOR_GRAY_LINE,textInputRightBtnColor:FONT_COLOR_SUB_TITLE})
                                                                }else{
                                                                    this.setState({textInputNum : num.toString(),textInputLeftBtnColor:FONT_COLOR_SUB_TITLE,textInputRightBtnColor:FONT_COLOR_SUB_TITLE})
                                                                }
                                                            }
                                                        }} size={25} style={{color: this.state.textInputLeftBtnColor}}/>
                                                        <TextInput style={styles.modalInput}
                                                                   keyboardType='numeric'
                                                                   textAlign='center'
                                                                   onChangeText={text => {
                                                                       if(Number(text)<0){
                                                                           text = '1'
                                                                       }
                                                                       this.setState({
                                                                           textInputNum : text,
                                                                       })
                                                                   }}
                                                                   defaultValue={this.state.textInputNum}
                                                        />
                                                        <AntDesign name={'pluscircle'} onPress={()=>{
                                                            let num = Number(this.state.textInputNum)+1;
                                                            if(num<=this.state.recordClickModalQuantity){
                                                                if(num===this.state.recordClickModalQuantity){
                                                                    this.setState({textInputNum : num.toString(),textInputRightBtnColor:COLOR_GRAY_LINE,textInputLeftBtnColor:FONT_COLOR_SUB_TITLE})
                                                                }else{
                                                                    this.setState({textInputNum : num.toString(),textInputRightBtnColor:FONT_COLOR_SUB_TITLE,textInputLeftBtnColor:FONT_COLOR_SUB_TITLE})
                                                                }
                                                            }

                                                        }} size={25} style={{color: this.state.textInputRightBtnColor}}/>
                                                    </View>
                                                )
                                            }
                                        </View>
                                        <View style={styles.modalBottom}>
                                            <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                                this.setState({
                                                    recordClickModal:false,
                                                })
                                            }}>
                                                <View style={styles.modalBottomLeft}>
                                                    <Text style={styles.modalBottomLeftText}>
                                                        取消
                                                    </Text>
                                                </View>
                                            </TouchableOpacity>
                                            <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                                let _this = this;
                                                AsyncStorage.getItem('chooseConsumables' ,function (error, result) {
                                                    if (error) {
                                                        alert('读取失败')
                                                    }else {
                                                        let newJSON = JSON.parse(result);

                                                        if(_this.state.recordClickModalSn in newJSON){
                                                            if(_this.state.selectState==="出仓"){
                                                                newJSON[_this.state.recordClickModalSn].quantity = _this.state.textInputNum
                                                            }else if(_this.state.selectState==="返仓"){
                                                                newJSON[_this.state.recordClickModalSn].quantity = '-'+_this.state.textInputNum
                                                            }
                                                        }else{
                                                            if(_this.state.selectState==="出仓"){
                                                                newJSON[_this.state.recordClickModalSn] = {"sn":_this.state.recordClickModalSn,"quantity":_this.state.textInputNum}
                                                            }else if(_this.state.selectState==="返仓"){
                                                                newJSON[_this.state.recordClickModalSn] = {"sn":_this.state.recordClickModalSn,"quantity":'-'+_this.state.textInputNum}
                                                            }
                                                        }
                                                        AsyncStorage.setItem('chooseConsumables',JSON.stringify(newJSON));
                                                        let newRecordSumString = JSON.stringify(_this.state.recordSum);
                                                        let newRecordSumJson =  JSON.parse(newRecordSumString);

                                                        let newRecordJSON = {};
                                                        newRecordSumJson.map((value,index)=>{
                                                            newRecordJSON[(value.sn)] = value
                                                        })

                                                        // console.log("storage------------"+JSON.stringify(newJSON));
                                                        // console.log("newRecordSumJson------------"+JSON.stringify(newRecordJSON));

                                                        for(let p in newJSON){//遍历json对象的每个key/value对,p为key
                                                            if(p in newRecordJSON){
                                                                newRecordJSON[p].balance= Number(newRecordJSON[p].balance)+Number(newJSON[p].quantity)
                                                                if(Number(newJSON[p].quantity)>0){
                                                                    newRecordJSON[p].doText = "本次出仓："+newJSON[p].quantity
                                                                }else if(Number(newJSON[p].quantity)===0){
                                                                    newRecordJSON[p].doText = "本次无操作"
                                                                }else if(Number(newJSON[p].quantity)<0){
                                                                    newRecordJSON[p].doText = "本次返仓："+Math.abs(Number(newJSON[p].quantity));
                                                                }

                                                            }
                                                        }

                                                        let resultArr = []
                                                        for(let q in newRecordJSON){
                                                            resultArr.push(newRecordJSON[q])
                                                        }

                                                        _this.setState({
                                                            newRecordSum:resultArr,
                                                            recordClickModal:false,
                                                        })
                                                        console.log(JSON.stringify(newJSON))
                                                    }
                                                })
                                            }}>
                                                <View style={styles.modalBottomRight}>
                                                    <Text style={styles.modalBottomRightText}>
                                                        确定
                                                    </Text>
                                                </View>
                                            </TouchableOpacity>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </TouchableOpacity>
                    </Modal>
                </SafeAreaView>
            )
        }

    }

    onRequestClose(){
        this.setState({
            recordClickModal:false
        })
    }

    _selectState=(value)=>{
        if(this.state.selectState===value){
            return(
                <View style={styles.modalItemViewRight}>
                    <MaterialCommunityIcons name={'radiobox-marked'} size={25} />
                </View>
            )
        }else{
            return(
                <View style={styles.modalItemViewRight}>
                    <MaterialCommunityIcons name={'radiobox-blank'} size={25} />
                </View>
            )
        }
    }

    getNewRecordSum=(data)=>{//data=>{"sn":"2","quantity":"1"}
        let _this = this;
        AsyncStorage.getItem('chooseConsumables' ,function (error, result) {
            if (error) {
                alert('读取失败')
            }else {
                let newJSON = JSON.parse(result);
                newJSON[(data.sn)] = data;
                AsyncStorage.setItem('chooseConsumables',JSON.stringify(newJSON));
                let newRecordSumString = JSON.stringify(_this.state.recordSum);
                let newRecordSumJson =  JSON.parse(newRecordSumString);

                let newRecordJSON = {};
                newRecordSumJson.map((value,index)=>{
                    newRecordJSON[(value.sn)] = value
                })

                // console.log("storage------------"+JSON.stringify(newJSON));
                // console.log("newRecordSumJson------------"+JSON.stringify(newRecordJSON));

                for(let p in newJSON){//遍历json对象的每个key/value对,p为key
                    if(p in newRecordJSON){
                        newRecordJSON[p].balance= Number(newRecordJSON[p].balance)+Number(newJSON[p].quantity)
                        newRecordJSON[p].doText = "本次出仓："+newJSON[p].quantity
                    }else{
                        newRecordJSON[p] = newJSON[p]
                        newRecordJSON[p].balance= Number(newJSON[p].quantity)
                        newRecordJSON[p].doText = "本次出仓："+newJSON[p].quantity
                    }
                }

                let resultArr = []
                for(let q in newRecordJSON){
                    resultArr.push(newRecordJSON[q])
                }

                _this.setState({
                    newRecordSum:resultArr,
                })
            }
        })
    };

    showRecordVisiable=()=>{
        this.setState({
            chooseConsumablesVisiable:false,
            recordVisiable:true,
        })
    };

    finishAdd=()=>{
        let {dispatch} = this.props;
        let _this = this;
        AsyncStorage.getItem('chooseConsumables' ,function (error, result) {
            if (error) {
                alert('读取失败')
            }else {
                let newJSON = JSON.parse(result);
                let outArr = [];

                for(let p in newJSON){//遍历json对象的每个key/value对,p为key
                    outArr.push({"sn":newJSON[p].sn,"quantity":newJSON[p].quantity})
                }
                // console.log(JSON.stringify(outArr))
                let str = {"arg":{"record_sn":_this.props.navigation.getParam("sn")},"qms_material_record":outArr};
                dispatch(materialRecordOut(JSON.stringify(str)))
            }
        })
    };

    _renderRecord=(value, index)=>{ //列表循环
        return(
            <TouchableOpacity key={index} activeOpacity={0.8}  onPress={() => {
                let balance=0;
                this.state.recordSum.map((vv,kk)=>{
                    if(vv.sn===value.sn){
                        balance = vv.balance
                    }
                });
                this.setState({recordClickModalQuantity:balance,recordClickModalSn:value.sn});
                let {dispatch} = this.props;
                let str = {"arg":{"SQLfields":""},"where":{"parent_sn":value.sn}};
                dispatch(retrieveMaterialBySn(JSON.stringify(str)));
            }}>
                <View style={styles.contentBox} onPress={()=>{

                }}>
                    <View style={styles.contentTop}>
                        <View style={styles.topLeft}>
                            <Text style={styles.topLeftText}>
                                {value.name}
                            </Text>
                        </View>
                        <View style={styles.topRight}>
                            <Text style={styles.topRightText}>
                                x{value.balance}
                            </Text>
                        </View>
                    </View>

                    <View style={styles.contentCenter}>
                        <Text style={styles.centerText}>
                            {
                                value.doText?value.doText:"本次无操作"
                            }
                        </Text>
                    </View>

                </View>
            </TouchableOpacity>
        )
    };

}

const props = state => {
    return {
        onGetRecordSum:state.onGetRecordSum,
        onMaterialRecordOut:state.onMaterialRecordOut,
        onRetrieveMaterialBySn:state.onRetrieveMaterialBySn,
    }
};

export default ConsumablesScreen = connect(props)(ConsumablesScreen);
